package com.seu.githubcn.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.githubcn.config.Result;
import com.seu.githubcn.entity.*;
import com.seu.githubcn.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 处理所有 Issue 相关的请求。
 */
@RestController
@RequestMapping
public class IssueController {
    @Autowired
    IssueMapper issueMapper;

    @Autowired
    RepoMapper repoMapper;

    @Autowired
    ManagerMapper managerMapper;

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    UserMapper userMapper;

    @PostMapping("/repo/create_issue")
    public Result<?> newIssue(@RequestBody Issue issue){
        User user =
                userMapper.selectOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getUserId,issue.getPosterId()));
        Repo repo =
                repoMapper.selectOne(Wrappers.<Repo>lambdaQuery()
                        .eq(Repo::getRepoName, issue.getRepoName())
                        .eq(Repo::getOwnerId,user.getUserId()));
        Issue newOne = new Issue();
        newOne.setRepoId(repo.getRepoId());
        newOne.setPosterId(issue.getPosterId());
        newOne.setIsClosed(false);
        newOne.setIsPulled(false);
        newOne.setIsRead(false);
        newOne.setIssueTitle(issue.getIssueTitle());
        newOne.setIssueContent(issue.getIssueContent());
        issueMapper.insert(newOne);


        var managerList =
                managerMapper.selectList(Wrappers.<Manager>lambdaQuery()
                        .eq(Manager::getRepoId,repo.getRepoId()));
        for(var manager:managerList){
            Message message = new Message();
            message.setTitle("您有新的工单，请查看！");
            message.setContent("您的仓库%s由%s创建了一个工单，请及时处理！".formatted(repo.getRepoName(),user.getUserName()));
            message.setUserId(manager.getManagerId());
            message.setStatus(true);
            messageMapper.insert(message);
        }



        return new Result<>(200,null,"新增成功！");
    }

    @GetMapping("/repo/issues")
    public Result<?> getMyIssues(@RequestParam(defaultValue = "1") Integer currentPage,
                                      @RequestParam(defaultValue = "10")Integer pageSize,
                                      @RequestParam(defaultValue = "0") String repoName,
                                      @RequestParam(defaultValue = "0") String ownerName,
                                      @RequestParam(defaultValue = "0") String searchMode){
        Repo repo =
                repoMapper.selectOne(Wrappers.<Repo>lambdaQuery()
                        .eq(Repo::getRepoName, repoName)
                        .eq(Repo::getOwnerName,ownerName));
        Integer repoId = repo.getRepoId();
        Integer mode=Integer.parseInt(searchMode);
        Page<Issue> issuePage;
        if(mode==0){
            issuePage =
                    issueMapper.selectPage(new Page<>(currentPage,pageSize),
                            Wrappers.<Issue>lambdaQuery()
                                    .eq(Issue::getRepoId,repoId).eq(Issue::getIsClosed,false));
        }
        else {
            issuePage =
                    issueMapper.selectPage(new Page<>(currentPage,pageSize),
                            Wrappers.<Issue>lambdaQuery()
                                    .eq(Issue::getRepoId,repoId).eq(Issue::getIsClosed,true));
        }
        for(var issue : issuePage.getRecords()){
            User poster = userMapper.selectById(issue.getPosterId());
            issue.setPostName(poster.getUserName());
        }
        return new Result<>(200,issuePage,"查询成功!");


    }
    /**
     * 获取工党内容
     *
     * @param issueId    目标工单的 ID。
     * @return 对应工单。
     */
    @GetMapping("/issues/get")
    public Result<?> getMyIssues(@RequestParam String issueId){
        Integer id= Integer.parseInt(issueId);
        Issue require =
               issueMapper.selectById(id);
        User poster = userMapper.selectById(require.getPosterId());
        require.setPostName(poster.getUserName());
        return new Result<>(200,require,"查询成功!");
    }


    /**
     * 获取某用户的全部相关 Issues。映射到 {@code /user/issues}
     *
     * @param userIds     目标用户的 ID。
     * @param searchModes 搜索模式。0 为搜索全部 Issue，1 为仅 open 状态的。
     * @return 搜索结果。
     */
    @GetMapping("/user/issues")
    public Result<Object> getMyIssues(
            @RequestParam(defaultValue = "0") String userIds,
            @RequestParam(defaultValue = "0") String searchModes
    ) {
        Integer userId=Integer.parseInt(userIds);
        Integer searchMode=Integer.parseInt(searchModes);
        List<Issue> issueList;
        if (searchMode==0) {
            issueList =
                    issueMapper.selectList(Wrappers.<Issue>lambdaQuery()
                            .eq(Issue::getPosterId, userId).eq(Issue::getIsClosed,false));
        }
        else {
            issueList =
                    issueMapper.selectList(Wrappers.<Issue>lambdaQuery()
                            .eq(Issue::getPosterId, userId).eq(Issue::getIsClosed,true));
        }
        for(var issue :  issueList){
            Repo repo = repoMapper.selectById(issue.getRepoId());
            issue.setRepoName(repo.getRepoName());
            issue.setRepoOwnerName(repo.getOwnerName());
        }
        return new Result<>(200,issueList,"查詢成功！");

    }
}
